package com.useeinfo.oa.modules.repair.biz;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.*;
import com.useeinfo.oa.common.config.ConstantKeyFilePath;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.NumberUtil;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.enums.MessageTypeEnum;
import com.useeinfo.oa.modules.base.enums.NodeTypeEnum;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.base.vo.MessageVO;
import com.useeinfo.oa.modules.inspection.entity.InspectionOrder;
import com.useeinfo.oa.modules.repair.dao.RepairOrderDao;
import com.useeinfo.oa.modules.repair.entity.*;
import com.useeinfo.oa.modules.repair.enums.*;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemAuthorityBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.biz.UserDeviceBiz;
import com.useeinfo.oa.modules.security.entity.SystemAuthority;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.entity.UserDevice;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.threadUtil.ThreadUtils;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.Warning;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.WarningDetail;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.WarningGroup;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Result;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * @Auther: xudong.sun
 * @Date: 2018/12/4 11:09
 * @Description:
 */
@Service("repairOrderBiz")
public class RepairOrderBiz extends CrudBiz<RepairOrderDao, RepairOrder> {

    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private RepairPartnerBiz repairPartnerBiz;
    @Autowired
    private RepairOrderLogBiz repairOrderLogBiz;
    @Autowired
    private RepairFocusBiz repairFocusBiz;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private AuditFlowBiz auditFlowBiz;
    @Autowired
    private ResourceBiz resourceBiz;
    @Autowired
    private DictInfoBiz dictInfoBiz;
    @Autowired
    private RepairLevelBiz repairLevelBiz;
    @Autowired
    private SystemUserOrganizationBiz systemUserOrganizationBiz;
    @Autowired
    private TroubleCatBiz troubleCatBiz;
    @Autowired
    private SystemAuthorityBiz systemAuthorityBiz;
    @Autowired
    private AreaBiz areaBiz;
    @Autowired
    private PlanMessageSendBiz planMessageSendBiz;

    public ResultDto addRepairPC(RepairOrder repairOrder, String reportType, String createDate, String majorName,
                                 String repairFinishTime1,
                                 String presenceTime1,
                                 String selectFacilityId,
                                 String selectAreaId,
                                 String selectUserId,
                                 String recording,
                                 String troubleCatId,
                                 String receiveUserId,
                                 String chargeUserId,
                                 String telephoneUserId,
                                 String repairOrderStatusEnum,
                                 String selectRepairTypeId,
                                 String selectReportLevelId,
                                 String selectOrganizationId,
                                 String selectCompleteAuditFlowId,
                                 String sImg1,
                                 String sImg2,
                                 String sImg3,
                                 String sImg4,
                                 String sImg5,
                                 MultipartFile pic1,
                                 MultipartFile pic2,
                                 MultipartFile pic3,
                                 MultipartFile pic4,
                                 MultipartFile pic5,
                                 String selectEnterpriseId,
                                 String selectSrc,
                                 String selectRecordingPath,
                                 String position,
                                 SystemUser systemUser,
                                 String selectTelephoneUser
    ) {

        SystemUser loginUser = SessionKeyUtils.getSessionUser(httpServletRequest);


        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (StringUtils.isBlank(selectUserId)) {
            return ResultUtil.error("请选择报修人");
        }
        repairOrder.setReportCode(getCode(StringConverters.null2String(SessionKeyUtils.getSessionEnterprise(httpServletRequest).getId())));
        repairOrder.setPosition(position);

        //根据紧急程度配置需要到场时间，需要完成时间
        Date now = new Date();
        if (StringUtils.isNotBlank(selectReportLevelId)) {
            RepairLevel repairLevel = repairLevelBiz.findModel(StringConverters.null2Long(selectReportLevelId));
                repairOrder.setReportLevel(repairLevel);
                repairOrder.setRequirePresenceTime(new Date(now.getTime() + repairLevel.getPresenceTime() * 60 * 1000));
                repairOrder.setRequireFinishTime(new Date(now.getTime() + repairLevel.getFinishTime() * 60 * 1000));
        } else {
            repairOrder.setRequirePresenceTime(new Date(now.getTime() + StringConverters.null2Long(Configuration.getConfigurationByName("defaultRequirePresenceTime")) * 60 * 1000));
            repairOrder.setRequireFinishTime(new Date(now.getTime() + StringConverters.null2Long(Configuration.getConfigurationByName("defaultRequireFinishTime")) * 60 * 1000));
        }

        if (StringUtils.isNotBlank(createDate)) {
            repairOrder.setCreateDate(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", createDate));
        }

        if (StringUtils.isNotBlank(repairFinishTime1)) {
            repairOrder.setRepairFinishTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", repairFinishTime1));
        }

        if (StringUtils.isNotBlank(presenceTime1)) {
            repairOrder.setPresenceTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", presenceTime1));
        }
        if ("_400_ORDER".equals(reportType)) {
            repairOrder.setRepairOrderTypeEnum(RepairOrderTypeEnum._400_ORDER);
            if (StringUtils.isNotBlank(selectRecordingPath)) {
                repairOrder.setRecordingPath(selectRecordingPath);
            }
            if (StringUtils.isNotBlank(selectSrc)) {
                repairOrder.setSrc(selectSrc);
            }
            repairOrder.setTelephoneUser(systemUserBiz.findModel(StringConverters.null2Long(selectTelephoneUser)));
        } else {

            if (StringUtils.isNotBlank(selectFacilityId)) {
                repairOrder.setRepairOrderTypeEnum(RepairOrderTypeEnum.FACILITY_ORDER);
            } else {
                repairOrder.setRepairOrderTypeEnum(RepairOrderTypeEnum.COMMON_ORDER);
            }
        }
        repairOrder.setEnterprise(enterprise);
        String savePath1 = FileUtils.fileUpload(pic1, ConstantKeyFilePath.FILE_UPLOAD_ROOT_PATH, ConstantKeyFilePath.REPAIR_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
        String savePath2 = FileUtils.fileUpload(pic2, ConstantKeyFilePath.FILE_UPLOAD_ROOT_PATH, ConstantKeyFilePath.REPAIR_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
        String savePath3 = FileUtils.fileUpload(pic3, ConstantKeyFilePath.FILE_UPLOAD_ROOT_PATH, ConstantKeyFilePath.REPAIR_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
        String savePath4 = FileUtils.fileUpload(pic4, ConstantKeyFilePath.FILE_UPLOAD_ROOT_PATH, ConstantKeyFilePath.REPAIR_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
        String savePath5 = FileUtils.fileUpload(pic5, ConstantKeyFilePath.FILE_UPLOAD_ROOT_PATH, ConstantKeyFilePath.REPAIR_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
        if (repairOrder.getId() != null  ) {
            if(CollectionUtils.isNotEmpty(dao.findModel(repairOrder.getId()).getReportPhoto())){
                List<Resource> repairOrders = new ArrayList<>(dao.findModel(repairOrder.getId()).getReportPhoto());
                repairOrders.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
                if ("1".equals(sImg1)) {
                    if (StringUtils.isNotBlank(savePath1)) {
                        Resource resource1 = new Resource();
                        resource1.setPath(savePath1);
                        resource1.setResourceName("报修图片");
                        resource1.setResourceTypeEnum(ResourceTypeEnum.IMG);
                        resource1.setEnterprise(enterprise);
                        resourceBiz.addOrUpdate(resource1);
                        repairOrders.set(0, resource1);
                    } else {
                        repairOrders.remove(0);
                    }
                }

                if ("1".equals(sImg2)) {
                    if (StringUtils.isNotBlank(savePath2)) {
                        Resource resource2 = new Resource();
                        resource2.setPath(savePath2);
                        resource2.setResourceName("报修图片");
                        resource2.setResourceTypeEnum(ResourceTypeEnum.IMG);
                        resource2.setEnterprise(enterprise);
                        resourceBiz.addOrUpdate(resource2);
                        if (repairOrders.size() == 1) {
                            repairOrders.add(resource2);
                        } else {
                            repairOrders.set(1, resource2);
                        }
                    } else {
                        repairOrders.remove(1);
                    }
                }

                if ("1".equals(sImg3)) {
                    if (StringUtils.isNotBlank(savePath3)) {
                        Resource resource3 = new Resource();
                        resource3.setPath(savePath3);
                        resource3.setResourceName("报修图片");
                        resource3.setEnterprise(enterprise);
                        resource3.setResourceTypeEnum(ResourceTypeEnum.IMG);
                        resourceBiz.addOrUpdate(resource3);
                        if (repairOrders.size() == 2) {
                            repairOrders.add(resource3);
                        } else {
                            repairOrders.set(2, resource3);
                        }
                    } else {
                        repairOrders.remove(2);
                    }
                }

                if ("1".equals(sImg4)) {
                    if (StringUtils.isNotBlank(savePath4)) {
                        Resource resource4 = new Resource();
                        resource4.setPath(savePath4);
                        resource4.setResourceName("报修图片");
                        resource4.setEnterprise(enterprise);
                        resource4.setResourceTypeEnum(ResourceTypeEnum.IMG);
                        resourceBiz.addOrUpdate(resource4);
                        if (repairOrders.size() == 3) {
                            repairOrders.add(resource4);
                        } else {
                            repairOrders.set(3, resource4);
                        }
                    } else {
                        repairOrders.remove(3);
                    }
                }

                if ("1".equals(sImg5) && StringUtils.isNotBlank(savePath5)) {
                    if (StringUtils.isNotBlank(savePath5)) {
                        Resource resource5 = new Resource();
                        resource5.setPath(savePath5);
                        resource5.setEnterprise(enterprise);
                        resource5.setResourceName("报修图片");
                        resource5.setResourceTypeEnum(ResourceTypeEnum.IMG);
                        resourceBiz.addOrUpdate(resource5);
                        if (repairOrders.size() == 4) {
                            repairOrders.add(resource5);
                        } else {
                            repairOrders.set(4, resource5);
                        }
                    } else {
                        repairOrders.remove(4);
                    }
                }
                repairOrder.setReportPhoto(new HashSet<>(repairOrders));
            }
            if (StringUtils.isNotBlank(recording)) {
                repairOrder.setResource(resourceBiz.findModel(StringConverters.null2Long(recording)));
            }

            if (StringUtils.isNotBlank(troubleCatId)) {
                repairOrder.setTroubleCat(troubleCatBiz.findModel(StringConverters.null2Long(troubleCatId)));
            }

            if (StringUtils.isNotBlank(telephoneUserId)) {
                repairOrder.setTelephoneUser(systemUserBiz.findModel(StringConverters.null2Long(telephoneUserId)));
            }

            if (StringUtils.isNotBlank(chargeUserId)) {
                repairOrder.setChargeUser(systemUserBiz.findModel(StringConverters.null2Long(chargeUserId)));
            }

            if (StringUtils.isNotBlank(receiveUserId)) {
                repairOrder.setReceiveUser(systemUserBiz.findModel(StringConverters.null2Long(receiveUserId)));
            }

            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.getEnum(repairOrderStatusEnum));
        } else {
            repairOrder.setAssign(false);
            //状态设置为待接单
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.WAIT_TAKING);

            Set<Resource> resourceSet = new HashSet<>();
            if (StringUtils.isNotEmpty(savePath1)) {
                Resource resource1 = new Resource();
                resource1.setPath(savePath1);
                resource1.setResourceName("报修图片");
                resource1.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource1);
                resourceSet.add(resource1);
            }

            if (StringUtils.isNotEmpty(savePath2)) {
                Resource resource2 = new Resource();
                resource2.setPath(savePath2);
                resource2.setResourceName("报修图片");
                resource2.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource2);
                resourceSet.add(resource2);
            }

            if (StringUtils.isNotEmpty(savePath3)) {
                Resource resource3 = new Resource();
                resource3.setPath(savePath3);
                resource3.setResourceName("报修图片");
                resource3.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource3);
                resourceSet.add(resource3);
            }

            if (StringUtils.isNotEmpty(savePath4)) {
                Resource resource4 = new Resource();
                resource4.setPath(savePath4);
                resource4.setResourceName("报修图片");
                resource4.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource4);
                resourceSet.add(resource4);
            }

            if (StringUtils.isNotEmpty(savePath5)) {
                Resource resource5 = new Resource();
                resource5.setPath(savePath5);
                resource5.setResourceName("报修图片");
                resource5.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource5);
                resourceSet.add(resource5);
            }

            repairOrder.setReportPhoto(resourceSet);
        }

        repairOrder.setReportLevel(repairLevelBiz.findModel(StringConverters.null2Long(selectReportLevelId)));
        repairOrder.setRepairSourceEnum(RepairSourceEnum.CUSTOMER_REPORT);
        repairOrder.setOrganization(organizationBiz.findModel(StringConverters.null2Long(selectOrganizationId)));
        repairOrder.setFacility(facilityBiz.findModel(StringConverters.null2Long(selectFacilityId)));
        repairOrder.setReportArea(areaBiz.findModel(StringConverters.null2Long(selectAreaId)));

        SystemUser selectUser = systemUserBiz.findModel(StringConverters.null2Long(selectUserId));//报修人
        repairOrder.setReportUser(selectUser);
        repairOrder.setMobile(selectUser == null ? "" : selectUser.getMobile());
        repairOrder.setRepairType(dictInfoBiz.findModel(StringConverters.null2Long(selectRepairTypeId)));
        repairOrder.setMajorName(majorName);
        //审批流，没有则查看是否有默认审批流
        AuditFlow auditFlow1 = auditFlowBiz.findModel(StringConverters.null2Long(selectCompleteAuditFlowId));
        if (auditFlow1 != null) {
            String newFlow = auditFlowBiz.updateFlowBySelf(enterprise.getId(), selectUser.getId(), auditFlow1.getFlow());
            repairOrder.setAuditFlow(auditFlow1);
            repairOrder.setLevel(auditFlow1.getLevel());
            repairOrder.setFlow(newFlow);
            repairOrder.setFlowName(auditFlow1.getFlowName());
            JSONArray jsonArray = JSON.parseArray(newFlow);
            if (jsonArray.size() > 0) {
                repairOrder.setAuditOrganization(null);
                repairOrder.setAuditUser(null);
                repairOrder.setAuditPosition(null);
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                repairOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                if (NodeTypeEnum.POSITION.getCode().equals(nodeTypeEnum)) {
                    repairOrder.setAuditPosition(positionBiz.findModel(relationId));
                } else if (NodeTypeEnum.USER.getCode().equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUserBiz.findModel(relationId));
                } else if (NodeTypeEnum.SELF.getCode().equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUser);
                }
            }
        } else {
            QueryParam auditFlowParam = new QueryParam();
            auditFlowParam.getSqlMap().put("isDefaultV", StringConverters.null2String(true));
            auditFlowParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
            auditFlowParam.getSqlMap().put("remark", "REPAIR");
            List<AuditFlow> auditFlows = auditFlowBiz.findList(auditFlowParam);
            if (CollectionUtils.isNotEmpty(auditFlows)) {
                AuditFlow auditFlow = auditFlows.get(0);
                String newFlow = auditFlowBiz.updateFlowBySelf(enterprise.getId(), selectUser.getId(), auditFlow.getFlow());
                repairOrder.setFlowName(auditFlow.getFlowName());
                repairOrder.setFlow(newFlow);
                JSONArray jsonArray = JSON.parseArray(newFlow);
                if (jsonArray.size() > 0) {
                    repairOrder.setAuditOrganization(null);
                    repairOrder.setAuditUser(null);
                    repairOrder.setAuditPosition(null);
                    JSONObject j = jsonArray.getJSONObject(0);
                    Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                    Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                    String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                    repairOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                    if ("POSITION".equals(nodeTypeEnum)) {
                        repairOrder.setAuditPosition(positionBiz.findModel(relationId));
                    } else if ("USER".equals(nodeTypeEnum)) {
                        repairOrder.setAuditUser(systemUserBiz.findModel(relationId));
                    }
                }
            }

        }


        //记录日志
        if (repairOrder.getId() != null){
            // 存在id，说明是修改
            repairOrderLogBiz.addLog(repairOrder, loginUser, RepairOrderLogOperationEnum.CHANGE_ORDER, enterprise, null);
        } else {
            repairOrderLogBiz.addLog(repairOrder, selectUser, RepairOrderLogOperationEnum.CREATE_ORDER, enterprise, null);
        }


        addOrUpdate(repairOrder);



        //发送消息
        List<Long> ids = new ArrayList<>();
        List<SystemUser> systemUsers1 = dao.sendRepairUsers(repairOrder, enterprise, null);
        String takingAuthority = Configuration.getConfigurationByName("repairAuthorityName");
        for (SystemUser user : systemUsers1) {
            if (systemAuthorityBiz.hasAuthAuthority(takingAuthority, user.getId(), enterprise.getId())) {//有接单权限
                ids.add(user.getId());
            }
        }
        if (ids.size() > 0) {
            planMessageSendBiz.senMsg(repairOrder.getId(), "repair", enterprise, ids, "维修单:" + repairOrder.getReportCode() + "已发布，请尽快接单");
        }

        return ResultUtil.success();
    }


    public String getCode(String enterpriseId) {
        return dao.getCode(enterpriseId);
    }

    public String dashBoardInfo(String enterpriseId, String status, String date) {
        return dao.dashBoardInfo(enterpriseId, status, date);
    }

    public JSONArray getbetween(String enterpriseId, String start, String end, int type, boolean completed) {
        return dao.getbetween(enterpriseId, start, end, type, completed);
    }

    public List<Object> getOrganizationReceiveNum(String organizationId, String start, String end) {
        return dao.getOrganizationReceiveNum(organizationId, start, end);
    }

    public ResultDto areaList(String pageIndex, String pageSize, String searchParam) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("magicLike", searchParam);
        List<Area> list = areaBiz.findList(queryParam);
        JSONArray jsonArray = new JSONArray();
        for (Area area : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", StringConverters.null2Long(area.getId()));
            String ids = area.getParentIds();
            StringBuilder names = new StringBuilder();
            if (StringUtils.isNotBlank(ids)) {
                String[] split = ids.split(",");
                for (String id : split) {
                    String name = areaBiz.findModel(StringConverters.null2Long(id)).getAreaName();
                    names.append(name).append("/");
                }
                names.append(area.getAreaName());
                jsonObject.put("names", names);
            } else {
                jsonObject.put("names", area.getAreaName());
            }
            jsonArray.add(jsonObject);
        }
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }


    /**
     * 设置维修单中的审批流信息
     */
    public RepairOrder setFlowInfo(RepairOrder repairOrder, AuditFlow auditFlow, SystemUser systemUser, Enterprise enterprise) {
        if (auditFlow != null && StringUtils.isNotBlank(auditFlow.getFlow())) {
            String newFlow = auditFlowBiz.updateFlowBySelf(systemUser.getId(), enterprise.getId(), auditFlow.getFlow());
            repairOrder.setFlowName(auditFlow.getFlowName());
            repairOrder.setFlow(newFlow);
            repairOrder.setLevel(auditFlow.getLevel());
            repairOrder.setAuditFlow(auditFlow);
            int auditLevel = repairOrder.getAuditLevel();
            JSONArray jsonArray = JSONArray.parseArray(newFlow);
            if (jsonArray.size() > 0 && auditLevel <= auditFlow.getLevel()) {
                repairOrder.setAuditUser(null);
                repairOrder.setAuditOrganization(null);
                repairOrder.setAuditPosition(null);
                JSONObject j = jsonArray.getJSONObject(auditLevel);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                repairOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                if ("POSITION".equals(nodeTypeEnum)) {
                    repairOrder.setAuditPosition(positionBiz.findModel(relationId));
                } else if ("USER".equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUserBiz.findModel(relationId));
                } else if ("SELF".equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUser);
                }
            }
        }
        return repairOrder;
    }

    /**
     * 创建维修单
     */
    public ResultDto addRepair(String assignUser, String assignPosition, String code, String reportContent, String reportAddress, String reportLevelId, String reportMajorId, String photos, String recordingId, String type, String areaId,
                               String facilityPosition, SystemUser systemUser, Enterprise enterprise,Date createDate) {
        List<Long> ids = new ArrayList<>();
        JSONArray userArray = JSONArray.parseArray(assignUser);
        JSONArray positionArray = JSONArray.parseArray(assignPosition);
        JSONObject result = new JSONObject();
        if (systemUser == null || enterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        if (StringUtils.isBlank(reportContent)) {
            return ResultUtil.error("请输入报修内容");
        }

        RepairOrder repairOrder = new RepairOrder();
        if(createDate!=null){
            repairOrder.setCreateDate(createDate);
        }
        repairOrder.setInRepairScope(true);//是否维修范围默认是
        repairOrder.setAssign(false);
        if (userArray.size() != 0 && positionArray.size() != 0) {
            return ResultUtil.error("指派只能选择一种类型");
        } else if (userArray.size() != 0) {
            repairOrder.setAssignTypeEnum(AssignTypeEnum.USER);
            Set<SystemUser> systemUserSet = new HashSet<>();
            for (Object x : userArray) {
                systemUserSet.add(systemUserBiz.findModel(StringConverters.null2Long(x)));
                ids.add(StringConverters.null2Long(x));
            }
            ;
            repairOrder.setAssignUsers(systemUserSet);
            repairOrder.setAssign(true);
        } else if (positionArray.size() != 0) {
            repairOrder.setAssignTypeEnum(AssignTypeEnum.POSITION);
            Set<Position> positionHashSet = new HashSet<>();
            for (Object x : positionArray) {
                positionHashSet.add(positionBiz.findModel(StringConverters.null2Long(x)));
                ids = systemUserBiz.getUserIdsByPosition(x.toString(),null, enterprise.getId() + "");
            }

            repairOrder.setAssign(true);
            repairOrder.setAssignPositions(positionHashSet);
        }


        repairOrder.setReportCode(dao.getCode(enterprise.getId().toString()));
        repairOrder.setInRoutingScope(true);
        if (StringUtils.isNotBlank(photos)) {
            Set<Resource> resourceSet = new HashSet<>();
            for (Object photoId : JSONArray.parseArray(photos)) {
                resourceSet.add(resourceBiz.findModel(StringConverters.null2Long(photoId)));
            }
            repairOrder.setReportPhoto(resourceSet);
        }

        if (StringUtils.isNotBlank(recordingId)) {
            repairOrder.setResource(resourceBiz.findModel(StringConverters.null2Long(recordingId)));
        }

        QueryParam systemUserOrganizationParam = new QueryParam();
        systemUserOrganizationParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
        List<SystemUserOrganization> systemUserOrganizations = systemUserOrganizationBiz.findList(systemUserOrganizationParam);
        if (CollectionUtils.isNotEmpty(systemUserOrganizations)) {
            repairOrder.setOrganization(systemUserOrganizations.get(0).getOrganization());
        }

        if ("0".equals(type)) {
            repairOrder.setRepairOrderTypeEnum(RepairOrderTypeEnum.COMMON_ORDER);
        } else if ("1".equals(type)) {
            repairOrder.setRepairOrderTypeEnum(RepairOrderTypeEnum.FACILITY_ORDER);
        }

        repairOrder.setRepairSourceEnum(RepairSourceEnum.CUSTOMER_REPORT);
        repairOrder.setEnterprise(enterprise);
        repairOrder.setReportUser(systemUser);
        repairOrder.setMobile(systemUser.getMobile());
        repairOrder.setReportContent(reportContent);
        repairOrder.setReportAddress(reportAddress);
        repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.WAIT_TAKING);
        repairOrder.setPosition(facilityPosition);
        //根据紧急程度配置需要到场时间，需要完成时间
        Date now = new Date();
        if (StringUtils.isNotBlank(reportLevelId)) {
            RepairLevel repairLevel = repairLevelBiz.findModel(StringConverters.null2Long(reportLevelId));
            repairOrder.setReportLevel(repairLevel);
            repairOrder.setRequirePresenceTime(new Date(now.getTime() + repairLevel.getPresenceTime() * 60 * 1000));
            repairOrder.setRequireFinishTime(new Date(now.getTime() + repairLevel.getFinishTime() * 60 * 1000));
        } else {
            repairOrder.setRequirePresenceTime(new Date(now.getTime() + StringConverters.null2Long(Configuration.getConfigurationByName("defaultRequirePresenceTime")) * 60 * 1000));
            repairOrder.setRequireFinishTime(new Date(now.getTime() + StringConverters.null2Long(Configuration.getConfigurationByName("defaultRequireFinishTime")) * 60 * 1000));
        }


        //审批流快照
        QueryParam auditFlowParam = new QueryParam();
        auditFlowParam.getSqlMap().put("isDefaultV", StringConverters.null2String(true));
        auditFlowParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        auditFlowParam.getSqlMap().put("remark", "REPAIR");
        List<AuditFlow> auditFlows = auditFlowBiz.findList(auditFlowParam);
        if (CollectionUtils.isNotEmpty(auditFlows)) {
            AuditFlow auditFlow = auditFlows.get(0);
            String newFlow = auditFlowBiz.updateFlowBySelf(enterprise.getId(), systemUser.getId(), auditFlow.getFlow());
            repairOrder.setFlowName(auditFlow.getFlowName());
            repairOrder.setFlow(newFlow);
            JSONArray jsonArray = JSON.parseArray(newFlow);
            if (jsonArray.size() > 0) {
                repairOrder.setAuditOrganization(null);
                repairOrder.setAuditUser(null);
                repairOrder.setAuditPosition(null);
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                repairOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                if ("POSITION".equals(nodeTypeEnum)) {
                    repairOrder.setAuditPosition(positionBiz.findModel(relationId));
                } else if ("USER".equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUserBiz.findModel(relationId));
                }
            }
        }

        //扫码添加设备区域
        if (StringUtils.isNotBlank(code)) {
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("code", code);
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
            List<Facility> facilities = facilityBiz.findList(queryParam);
            if (CollectionUtils.isEmpty(facilities)) {
                return ResultUtil.error();
            }
            Facility facility = facilities.get(0);
            if (facility.getArea() != null) {
                repairOrder.setReportArea(facility.getArea());
            }
            repairOrder.setFacility(facility);
            if (facility.getRootCatId() != null) {
                repairOrder.setMajorName(facilityCatBiz.findModel(facility.getRootCatId()).getCatName());
            }
        }

        if (StringUtils.isNotBlank(areaId)) {
            Area area = areaBiz.findModel(StringConverters.null2Long(areaId));
            repairOrder.setReportArea(area);
        }
        addOrUpdate(repairOrder);
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.CREATE_ORDER, enterprise, null);
        //消息推送
        List<Long> ides = new ArrayList<>();
        logger.info("ids长度为：{}", ids);
        List<SystemUser> systemUsers1 = dao.sendRepairUsers(repairOrder, enterprise, ids);
        String repairAuthorityName = Configuration.getConfigurationByName("repairAuthorityName");
        for (SystemUser user : systemUsers1) {
            if (systemAuthorityBiz.hasAuthAuthority(repairAuthorityName, user.getId(), enterprise.getId())) {
                ides.add(user.getId());
            }
        }
        if (ides.size() > 0) {
            planMessageSendBiz.senMsg(repairOrder.getId(), "repair", enterprise, ides, "维修单:" + repairOrder.getReportCode() + "已发布，请尽快接单");
        }else{
            logger.info("维修发单没有找到匹配的人员");
        }
        result.put("code", repairOrder.getReportCode());
        result.put("id", repairOrder.getId());
        return ResultUtil.success(result);
    }

    public ResultDto presence(String presencePhotos, String repairOrderId, String longitude, String latitude) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        if (StringUtils.isBlank(presencePhotos)) {
            return ResultUtil.error("请先拍照");
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("id", repairOrderId);
        List<RepairOrder> repairOrders = findList(queryParam);
        if (CollectionUtils.isEmpty(repairOrders)) {
            return ResultUtil.error("请传入正确的参数");
        }

        JSONArray photos = JSONArray.parseArray(presencePhotos);
        Set<Resource> set = new HashSet<>();
        for (Object object : photos) {
            Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
            resource.setEnterprise(sessionEnterprise);
            resource.setResourceName("到场照片");
            resourceBiz.addOrUpdate(resource);
            set.add(resource);
        }
        RepairOrder repairOrder = repairOrders.get(0);
        repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.WAIT_CONFIRM_FAULT);
        repairOrder.setPresencePhoto(set);
        repairOrder.setPresenceTime(new Date());
        repairOrder.setMark(false);
        if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
            logger.info("接收到的经纬度为：{}", longitude + "," + latitude);
            try {
                BigDecimal latitudeParam = new BigDecimal(latitude);
                BigDecimal longitudeParam = new BigDecimal(longitude);
                repairOrder.setLatitude(latitudeParam);
                repairOrder.setLongitude(longitudeParam);
            } catch (Exception e) {
                logger.info("获取经纬度异常");
            }
        }
        addOrUpdate(repairOrder);

        //日志
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.PRESENCE, sessionEnterprise, null);

        return ResultUtil.success();
    }

    public ResultDto confirmFault(String repairOrderId, String troubleCatId, String faultReason, Boolean inRepairScope) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        if (StringUtils.isBlank(repairOrderId)) {
            return ResultUtil.error("请传入正确的参数");
        }

        QueryParam orderParam = new QueryParam();
        orderParam.getSqlMap().put("id", repairOrderId);
        orderParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        List<RepairOrder> repairOrders = findList(orderParam);
        if (CollectionUtils.isEmpty(repairOrders)) {
            return ResultUtil.error();
        }

        RepairOrder repairOrder = repairOrders.get(0);

        if (StringUtils.isNotBlank(troubleCatId)) {
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("troubleCatId", troubleCatId);
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
            List<TroubleCat> troubleCats = troubleCatBiz.findList(queryParam);
            if (CollectionUtils.isNotEmpty(troubleCats)) {
                repairOrder.setTroubleCat(troubleCats.get(0));
            }
        }

        repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.UNFINISHED);
        repairOrder.setInRoutingScope(StringConverters.null2Boolean(inRepairScope));
        repairOrder.setFaultReason(StringConverters.null2String(faultReason));
        addOrUpdate(repairOrder);

        //日志
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.CONFIRM_FAULT, sessionEnterprise, null);
        return ResultUtil.success();
    }


    /**
     * 临时保存
     *
     * @param repairOrderId
     * @param spareParts
     * @param finishPhotos
     * @param unrepairReason
     * @param measure
     * @param faultReason
     * @param inRepairScope
     * @param troubleCatId
     * @param workingHours
     * @return
     */
    public ResultDto save(String repairOrderId, String spareParts, String finishPhotos, String unrepairReason, String measure, String faultReason, Boolean inRepairScope, String troubleCatId, String workingHours) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (StringUtils.isNotBlank(repairOrderId)) {
            RepairOrder repairOrder = findModel(StringConverters.null2Long(repairOrderId));
            repairOrder.setMeasure(StringConverters.null2String(measure));
            repairOrder.setSpareParts(StringConverters.null2String(spareParts));
            repairOrder.setUnrepairReason(StringConverters.null2String(unrepairReason));
            repairOrder.setFaultReason(StringConverters.null2String(faultReason));
            repairOrder.setInRoutingScope(StringConverters.null2Boolean(inRepairScope));
            if (StringUtils.isNotBlank(troubleCatId)) {
                repairOrder.setTroubleCat(troubleCatBiz.findModel(StringConverters.null2Long(troubleCatId)));
            }
            if (StringUtils.isNotBlank(finishPhotos)) {
                JSONArray photos = JSONArray.parseArray(finishPhotos);
                Set<Resource> set = new HashSet<>();
                for (Object object : photos) {
                    Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
                    resource.setEnterprise(sessionEnterprise);
                    resource.setResourceName("完成照片");
                    resourceBiz.addOrUpdate(resource);
                    set.add(resource);
                }
                repairOrder.setFinishPhoto(set);
            }
            repairOrder.setMark(true);
            repairOrder.setSaveTriggerTime(new Date());
            addOrUpdate(repairOrder);
        }
        return ResultUtil.success();
    }


    public ResultDto addPartner(String repairOrderId, String partnerArray) {
        JSONObject jsonObject = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (StringUtils.isNotBlank(partnerArray)) {
            JSONArray array = JSONArray.parseArray(partnerArray);
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < array.size(); i++) {
                JSONObject j = array.getJSONObject(i);

                String userId = AliJsonObjectCover.ObjectString(j, "userId");

                QueryParam queryParam = new QueryParam();
                queryParam.getSqlMap().put("partnerId", userId);
                queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
                queryParam.getSqlMap().put("repairOrderId", repairOrderId);
                List<RepairPartner> list = repairPartnerBiz.findList(queryParam);
                RepairPartner repairPartner;
                if (CollectionUtils.isNotEmpty(list)) {
                    repairPartner = list.get(0);
                } else {
                    repairPartner = new RepairPartner();
                }


                if (StringUtils.isNotBlank(repairOrderId)) {
                    RepairOrder repairOrder = findModel(StringConverters.null2Long(repairOrderId));
                    repairPartner.setRepairOrder(repairOrder);
                }
                repairPartner.setEnterprise(sessionEnterprise);
                String reason = AliJsonObjectCover.ObjectString(j, "reason");
                if (StringUtils.isNotBlank(reason)) {
                    repairPartner.setReason(reason);
                }
                String teamworkCatId = AliJsonObjectCover.ObjectString(j, "teamworkCatId");
                if (StringUtils.isNotBlank(teamworkCatId)) {
                    QueryParam dictInfoParam = new QueryParam();
                    dictInfoParam.getSqlMap().put("dictInfoId", StringConverters.null2String(teamworkCatId));
                    dictInfoParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise));
                    repairPartner.setTeamworkCat(CollectionUtils.isEmpty(dictInfoBiz.findList(dictInfoParam)) ? null : dictInfoBiz.findList(dictInfoParam).get(0));
                }

                if (StringUtils.isNotBlank(userId)) {
                    repairPartner.setPartner(systemUserBiz.findModel(StringConverters.null2Long(userId)));
                }

                repairPartnerBiz.addOrUpdate(repairPartner);
                jsonArray.add(repairPartner.getId());
            }
            jsonObject.put("partnerIds", jsonArray);
        }
        return ResultUtil.success(jsonObject);
    }

    public ResultDto upload(MultipartFile file, String type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (file == null || StringUtils.isBlank(type)) {
            return ResultUtil.error("参数错误");
        }
        Resource resource = new Resource();
        String savePath = "";
        if ("mp3".equals(type)) {
            savePath = FileUtils.fileUpload(file, ConstantKeyFilePath.REPAIR_MP3_DIR, ConstantKeyFilePath.REPAIR_MP3_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            resource.setResourceName("设备报修录音");
            resource.setResourceTypeEnum(ResourceTypeEnum.MP3);
        } else if ("img".equals(type)) {
            savePath = FileUtils.fileUpload(file, ConstantKeyFilePath.REPAIR_IMG_DIR, ConstantKeyFilePath.REPAIR_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            resource.setResourceName("设备报修图片");
            resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
        }
        resource.setPath(savePath);
        resource.setEnterprise(sessionEnterprise);
        resource.setCreateDate(new Date());
        resourceBiz.addOrUpdate(resource);
        return ResultUtil.success(resource.toJSONObject());
    }


    public ResultDto getRepairOrders(String pageIndex, String pageSize, String status, String searchParam, SystemUser systemUser, Enterprise enterprise, String date, String startDate, String endDate,String catId,String areaId,String levelId,String typeId,String repairPosition,String receiveUser) {

        systemUser = systemUserBiz.findModel(systemUser.getId());
        Position position = systemUser.getPosition(enterprise, systemUser.getPositionSet());
        Set<Long> areaIds = new HashSet<>();
        if (systemUser.getAreaSet() != null) {
            for (Area area : systemUser.getAreaSet()) {
                areaIds.add(area.getId());
            }
        }

        Set<SystemUserOrganization> systemUserOrganizationSet = systemUser.getSystemUserOrganizationSet();
        //所属部门
        Organization organization = null;
        boolean leader = false;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationSet)) {
            for(SystemUserOrganization x:systemUserOrganizationSet){
                if(x.getOrganization().getEnterprise().getId().equals(enterprise.getId())){
                    leader = x.isLeader();
                   organization=x.getOrganization();
                }
            }
        }
        String enterpriseId = StringConverters.null2String(enterprise.getId());
        String userId = StringConverters.null2String(systemUser.getId());
        return ResultUtil.success(dao.getRepairOrders(pageIndex, pageSize, enterpriseId, userId, areaIds, position == null ? null : StringConverters.null2String(position.getId()), status, leader, organization, searchParam, date,startDate,endDate,catId,areaId,levelId,typeId,repairPosition,receiveUser));
    }

    /**
     * 维修-确认完成
     */
    public ResultDto repairConfirm(RepairOrder repairOrder, JSONArray participantInputs, String spareParts, String finishPhotos, String unrepairReason, String measure, String repairFinishTime, String faultReason, Boolean inRepairScope, String troubleCatId) {

        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (repairOrder == null) {
            return ResultUtil.error("维修不存在！");
        }

        if (StringUtils.isNotBlank(finishPhotos)) {
            JSONArray photos = JSONArray.parseArray(finishPhotos);
            Set<Resource> set = new HashSet<>();
            for (Object object : photos) {
                Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
                resource.setEnterprise(sessionEnterprise);
                resource.setResourceName("完成照片");
                resourceBiz.addOrUpdate(resource);
                set.add(resource);
            }
            repairOrder.setFinishPhoto(set);
        }
        // 是否维修范围
        repairOrder.setInRoutingScope(StringConverters.null2Boolean(inRepairScope));
        if (StringUtils.isNotBlank(repairFinishTime)) {
            // 维修完成时间
            repairOrder.setRepairFinishTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", repairFinishTime));
        }

        if (StringUtils.isNotBlank(troubleCatId)) {
            // 故障分类
            repairOrder.setTroubleCat(troubleCatBiz.findModel(StringConverters.null2Long(troubleCatId)));
        }

        long totalWorkingHours = repairOrder.getTotalWorkingHours();

        repairOrder.setUnrepairReason(StringConverters.null2String(faultReason));
        repairOrder.setSpareParts(StringConverters.null2String(spareParts));
        repairOrder.setUnrepairReason(StringConverters.null2String(unrepairReason));
        repairOrder.setMeasure(StringConverters.null2String(measure));
        String signEnterpriseId=Configuration.getConfigurationByName("signEnterpriseId");//只有武汉通用才有签字
        //如果是400工单，不管是否有审批流，都进入审核状态，确认维修和签字之后判断是否进入审核中，没有则已完成
        if (signEnterpriseId.equals(sessionEnterprise.getId().toString())&&repairOrder.getRepairOrderTypeEnum().equals(RepairOrderTypeEnum._400_ORDER) || (repairOrder.getLevel() >= 0 && StringUtils.isNotBlank(repairOrder.getFlow()))) {
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.IN_AUDITING);
        } else {
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.COMPLETED);
        }
        //工时计算
        //最新增加的工时
        long thisHours = DateTimeUtils.newGetDiffMinutesTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", DateTimeUtils.format(repairOrder.getPresenceTime(), "yyyy-MM-dd HH:mm:ss")), new Date());
        repairOrder.setWorkingHours(repairOrder.getWorkingHours() + thisHours);
        repairOrder.setSaveTriggerTime(null);
        // 参与人
        List<RepairPartner> repairPartners = new ArrayList<>();
        if (participantInputs.size() > 0) {
            for (int i = 0; i < participantInputs.size(); i++) {
                JSONObject j = participantInputs.getJSONObject(i);
                Long workingHours = AliJsonObjectCover.ObjectLong(j, "workingHours");
                if (workingHours == null) {
                    return ResultUtil.error("工时不能为空！");
                }

                // 参与人工时不可大于主要负责人工时
                if (workingHours > thisHours){
                    repairOrder.setWorkingHours(repairOrder.getWorkingHours() - thisHours);
                    addOrUpdate(repairOrder);
                    return ResultUtil.error("参与人工时不可大于主要负责人工时");
                }



                totalWorkingHours += workingHours;
                Long partnerId = AliJsonObjectCover.ObjectLong(j, "userId");
                QueryParam q = new QueryParam();
                q.getSqlMap().put("partnerId", partnerId == null ? "-1" : partnerId + "");
                q.getSqlMap().put("repairOrderId", repairOrder.getId() + "");
                q.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
                List<RepairPartner> repairPartnerList = repairPartnerBiz.findList(q);
                if (CollectionUtils.isEmpty(repairPartnerList)) {
                    return ResultUtil.error("参与人不存在！");
                }
                RepairPartner repairPartner = repairPartnerList.get(0);
                repairPartner.setWorkingHours(repairPartner.getWorkingHours() + workingHours);
                repairPartners.add(repairPartner);
            }
        }
        repairOrder.setTotalWorkingHours(totalWorkingHours + thisHours);
        repairOrder.setRepairFinishTime(new Date());
        addOrUpdate(repairOrder);
        repairPartners.forEach(repairPartner -> repairPartnerBiz.addOrUpdate(repairPartner));
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.COMPLETE, sessionEnterprise, null);

        //消息推送
        String auditAuthority = "ROLE_ENTERPRISE_REPAIR_ORDER_AUDIT";
        String content = "维修工单:" + repairOrder.getReportCode() + "已完成";
        List<SystemUser> systemUsers = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        logger.info("审批流信息：{}", repairOrder.getFlow());
        if (repairOrder.getFlow() != null) {
            content = "维修工单:" + repairOrder.getReportCode() + "已完成,待审核";
            JSONArray jsonArray = JSONArray.parseArray(repairOrder.getFlow());
            if (jsonArray != null && jsonArray.size() > 0) {
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Organization organization = organizationBiz.findModel(StringConverters.null2Long(organizationId));
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                if ("POSITION".equals(nodeTypeEnum)) {
                    systemUsers = dao.confirmSendUser(sessionEnterprise, positionBiz.findModel(StringConverters.null2Long(relationId)), organization, null);
                } else if ("USER".equals(nodeTypeEnum)) {
                    systemUsers = dao.confirmSendUser(sessionEnterprise, null, organization, systemUserBiz.findModel(StringConverters.null2Long(relationId)));
                } else if ("SELF".equals(nodeTypeEnum)) {
                    systemUsers = dao.confirmSendUser(sessionEnterprise, null, organization, systemUser);
                }

                for (SystemUser systemUser1 : systemUsers) {
                    if (systemAuthorityBiz.hasAuthAuthority(auditAuthority, systemUser1.getId(), sessionEnterprise.getId())) {
                        ids.add(systemUser1.getId());
                    }
                }
            }
        }
        if (ids.size() > 0) {
            planMessageSendBiz.senMsg(repairOrder.getId(), "repair", sessionEnterprise, ids, content);
        }


        return ResultUtil.success();
    }

    /**
     * 转单
     */
    public ResultDto transfer(String repairOrderId, String userIds) {
        List<Long> ids = new ArrayList<>();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        RepairOrder repairOrder = findModel(StringConverters.ToLong(repairOrderId));
        String content = "工单:" + repairOrder.getReportCode() + "被转单,请接单";
        JSONArray jsonArray = JSONArray.parseArray(userIds);
        if (jsonArray.size() > 0) {
            repairOrder.setAssignPositions(null);
            repairOrder.setAssignUsers(null);
            repairOrder.setAssignTypeEnum(AssignTypeEnum.USER);
            repairOrder.setAssign(true);
            repairOrder.setTransfer(true);
            Set<SystemUser> user = new HashSet<>();
            for (Object id : jsonArray) {
                SystemUser model = systemUserBiz.findModel(StringConverters.null2Long(id));
                user.add(model);
                ids.add(model.getId());
            }
            repairOrder.setAssignUsers(user);
        }
        repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.WAIT_TAKING);
        addOrUpdate(repairOrder);
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.TRANSFER, sessionEnterprise, null);
        if (ids.size() > 0) {
            planMessageSendBiz.senMsg(repairOrder.getId(), "repair", sessionEnterprise, ids, content);
        }

        return ResultUtil.success();
    }


    /**
     * 关注/取消关注
     */
    public ResultDto focus(String repairOrderId, Boolean type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || enterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (type) {
            //关注
            RepairFocus repairFocus = new RepairFocus();
            repairFocus.setEnterprise(enterprise);
            repairFocus.setSystemUser(systemUser);
            repairFocus.setRepairOrder(dao.findModel(StringConverters.null2Long(repairOrderId)));
            repairFocusBiz.addOrUpdate(repairFocus);
        } else {
            //取消关注
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
            queryParam.getSqlMap().put("repairOrderId", repairOrderId);
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
            List<RepairFocus> repairFocusList = repairFocusBiz.findList(queryParam);
            for (RepairFocus repairFocus : repairFocusList) {
                repairFocusBiz.delete(repairFocus.getId());
            }
        }
        return ResultUtil.success();
    }


    public Boolean isFocus(String repairOrderId, SystemUser systemUser, Enterprise enterprise) {
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
        queryParam.getSqlMap().put("repairOrderId", repairOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        List<RepairFocus> repairFocusList = repairFocusBiz.findList(queryParam);
        if (CollectionUtils.isEmpty(repairFocusList)) {
            return false;
        }
        return true;
    }

    public ResultDto finalAudit(String repairOrderId, String remark, String score) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        RepairOrder repairOrder = findModel(StringConverters.null2Long(repairOrderId));
        repairOrder.setLastRemark(StringConverters.null2String(remark));
        repairOrder.setLastScore(StringConverters.null2Int(score));
        addOrUpdate(repairOrder);
        return ResultUtil.success();
    }

    /**
     * 审批
     */
    public ResultDto audit(String repairOrderId, Boolean type, String remark) {
        String content = "";
        JSONObject jsonObject = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        List<SystemUser> systemUsers = new ArrayList<>();
        RepairOrder repairOrder = dao.findModel(StringConverters.null2Long(repairOrderId));
        JSONArray jsonArray = JSONArray.parseArray(repairOrder.getFlow());
        List<Long> ids = new ArrayList<>();
        //审批通过，推送给接单人和下一级审批者
        if (type) {
            //维修单中的审批流快照
            int auditLevel = repairOrder.getAuditLevel();
            content = "维修单" + repairOrder.getReportCode() +"," + systemUser.getUserName() + "审核通过。";
            if (jsonArray.size() > 0 && auditLevel + 1 < jsonArray.size()) {
                repairOrder.setAuditLevel(auditLevel + 1);
                repairOrder.setAuditUser(null);
                repairOrder.setAuditOrganization(null);
                repairOrder.setAuditPosition(null);
                JSONObject j = jsonArray.getJSONObject(auditLevel + 1);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                repairOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                if ("POSITION".equals(nodeTypeEnum)) {
                    repairOrder.setAuditPosition(positionBiz.findModel(relationId));
                    systemUsers = dao.confirmSendUser(sessionEnterprise, positionBiz.findModel(StringConverters.null2Long(relationId)), organizationBiz.findModel(organizationId), null);
                } else if ("USER".equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUserBiz.findModel(relationId));
                    systemUsers = dao.confirmSendUser(sessionEnterprise, null, organizationBiz.findModel(organizationId), systemUserBiz.findModel(StringConverters.null2Long(relationId)));

                } else if ("SELF".equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(repairOrder.getReportUser());
                    systemUsers = dao.confirmSendUser(sessionEnterprise, null, organizationBiz.findModel(organizationId), systemUser);
                }
                jsonObject.put("final", false);
                repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.AUDIT, sessionEnterprise, null);
            } else if (jsonArray.size() > 0 && auditLevel + 1 >= jsonArray.size()) {
                jsonObject.put("final", true);
                content = "维修单" + repairOrder.getReportCode() + "已经审核通过。";
                repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.COMPLETED);
                repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.AUDIT, sessionEnterprise, null);
                repairOrderLogBiz.addLog(repairOrder, repairOrder.getReceiveUser(), RepairOrderLogOperationEnum.FINISH, sessionEnterprise, null);
            }

        } else {//驳回，推送给接单人
            int level = repairOrder.getAuditLevel() + 1;
            content = "维修单审核" + repairOrder.getReportCode() +"," + systemUser.getUserName() + "审核退回，请及时处理。";
            //退回重修
            jsonObject.put("final", false);
            repairOrder.setRepairFinishTime(null);
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.REJECTED);
            if (StringUtils.isBlank(remark)) {
                return ResultUtil.error("请输入驳回理由");
            }
            //如果是400,原来的签字图片删除；清空到场签字时间，维修确认时间 二期
            repairOrder.setSignDate(null);
            repairOrder.setConfirmDate(null);
            repairOrder.setCheckRepair(false);
            Set<Resource> resources = repairOrder.getFinishPhoto();
            if (CollectionUtils.isNotEmpty(resources)) {
                for(Resource resource:resources){
                    if (resource.getResourceName().equals("签字图片")) {
                        resources.remove(resource);
                        resourceBiz.deleteLogic(resource);
                        break;
                    }
                }
                repairOrder.setFinishPhoto(resources);
            }
            if (jsonArray.size() > 0) {
                repairOrder.setAuditUser(null);
                repairOrder.setAuditOrganization(null);
                repairOrder.setAuditPosition(null);
                repairOrder.setAuditLevel(0);
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                repairOrder.setAuditOrganization(organizationBiz.findModel(StringConverters.null2Long(organizationId)));
                if ("POSITION".equals(nodeTypeEnum)) {
                    repairOrder.setAuditPosition(positionBiz.findModel(StringConverters.null2Long(relationId)));
                } else if ("USER".equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUserBiz.findModel(StringConverters.null2Long(relationId)));
                } else if ("SELF".equals(nodeTypeEnum)) {
                }
            }
            repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.REJECT, sessionEnterprise, remark);

        }
        addOrUpdate(repairOrder);
        for (SystemUser systemUser1 : systemUsers) {
            ids.add(systemUser1.getId());
        }
        if(!ids.contains(repairOrder.getReceiveUser().getId())){
            ids.add(repairOrder.getReceiveUser().getId());
        }
        //推送消息
        if (ids.size() > 0) {
            planMessageSendBiz.senMsg(repairOrder.getId(), "repair", sessionEnterprise, ids, content);
        }
        return ResultUtil.success(jsonObject);
    }

    /**
     * 审批记录
     */
    public JSONArray aduitLog(String repairOrderId, Enterprise enterprise) {
        JSONArray result = new JSONArray();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("repairOrderId", repairOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        queryParam.getSqlMap().put("repairOrderLogOperation", "AUDIT,REJECT");
        queryParam.setSqlOrder(" order by id  ");
        RepairOrder repairOrder = findModel(StringConverters.null2Long(repairOrderId));
        List<RepairOrderLog> list = repairOrderLogBiz.findList(queryParam);
        for (RepairOrderLog repairOrderLog : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", StringConverters.null2String(repairOrderLog.getUserName()));
            if ("AUDIT".equals(repairOrderLog.getRepairOrderLogOperationEnum().getCode())) {
                jsonObject.put("operation", "审批通过");
                jsonObject.put("status", "AUDIT");
            } else if ("REJECT".equals(repairOrderLog.getRepairOrderLogOperationEnum().getCode())) {
                jsonObject.put("operation", "审批驳回");
                jsonObject.put("status", "REJECT");
                jsonObject.put("remark", StringConverters.null2String(repairOrderLog.getRemark()));
            }
            result.add(jsonObject);
        }
        return result;
    }


    /**
     * 维修单详情
     * @param repairOrderId 维修单id
     * @return ResultDto
     */
    public ResultDto repairOrderDetail(String repairOrderId) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (StringUtils.isBlank(repairOrderId)) {
            return ResultUtil.error("参数错误");
        }
        RepairOrder repairOrder = findModel(StringConverters.null2Long(repairOrderId));
        JSONObject jsonObject = repairOrder.toJSONObject();
        //工时计算
        net.sf.json.JSONObject workingTime = net.sf.json.JSONObject.fromObject(nowWorkHours(repairOrderId).getData());
        if (repairOrder.getRepairOrderStatusEnum().getCode().equals("UNFINISHED") || repairOrder.getRepairOrderStatusEnum().getCode().equals("REJECTED") || repairOrder.getRepairOrderStatusEnum().getCode().equals("WAIT_CONFIRM_FAULT")) {
            jsonObject.put("totalWorkingHours", workingTime.get("totalHours"));//总工时
            jsonObject.put("workingHour", workingTime.get("receiveHours"));//我的工时
            jsonObject.put("workingHours", workingTime.get("receiveHours"));//我的工时
        }
        jsonObject.put("beforeHours", repairOrder.getWorkingHours());//退回重修前的工时
        jsonObject.put("beforeTotalHours", repairOrder.getTotalWorkingHours());//退回重修前的总工时
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("repairOrderId", repairOrderId);

        JSONArray partnerArray = new JSONArray();
        List<RepairPartner> repairPartners = repairPartnerBiz.findList(queryParam);
        repairPartners.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
        if (CollectionUtils.isNotEmpty(repairPartners)) {
            for (RepairPartner repairPartner : repairPartners) {
                JSONObject partnerObject = new JSONObject();
                partnerObject.put("userName", repairPartner.getPartner().getUserName());
                partnerObject.put("userId", repairPartner.getPartner().getId());
                partnerObject.put("partnerId", repairPartner.getId());
                partnerObject.put("workingHours", repairPartner.getWorkingHours());
                partnerObject.put("deleteStatus", repairPartner.isDeleteStatus());
                partnerArray.add(partnerObject);
            }
        }
        jsonObject.put("partner", partnerArray);
        JSONArray jsonArray = new JSONArray();
        String statusCode = repairOrder.getRepairOrderStatusEnum().getCode();
        JSONArray flowArray = JSONArray.parseArray(repairOrder.getFlow());
        int auditLevel = repairOrder.getAuditLevel();
        systemUser = systemUserBiz.findModel(systemUser.getId());
        Set<SystemUserOrganization> systemUserOrganizationSet = systemUser.getSystemUserOrganizationSet();
        boolean leader = false;
        //所属部门
        Organization organization = null;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationSet)) {
            for(SystemUserOrganization x:systemUserOrganizationSet){
                if(x.getOrganization().getEnterprise().getId().equals(sessionEnterprise.getId())){
                    leader = x.isLeader();
                    organization=x.getOrganization();
                }
            }
        }
        String signEnterpriseId=Configuration.getConfigurationByName("signEnterpriseId");//只有武汉通用才有签字
        String takingAuthority = "ROLE_ENTERPRISE_REPAIR_ORDER_TAKING";
        String auditAuthority = "ROLE_ENTERPRISE_REPAIR_ORDER_AUDIT";
        String assignAuthorityName = "ROLE_ENTERPRISE_REPAIR_ORDER_ASSIGN";
        // 批量转单权限code
        String transfersHorityName = "ROLE_ENTERPRISE_REPAIR_BATCH_TRANSFER";



        if ("WAIT_TAKING".equals(statusCode)) {
            if (systemAuthorityBiz.hasAuthAuthority(assignAuthorityName, systemUser.getId(), sessionEnterprise.getId())) {
                jsonArray.add("assignButton");
            }
            if (repairOrder.getFacility() != null) {
                jsonArray.add("logButton");
            }

            if (systemAuthorityBiz.hasAuthAuthority(takingAuthority, systemUser.getId(), sessionEnterprise.getId())) {
                //指定接单人的，需要判断我发起的工单有没有指派
                Position position=systemUser.getPosition(sessionEnterprise,systemUser.getPositionSet());//获取当前企业下的职位
                if(repairOrder.getAssign()&&(repairOrder.getAssignUsers().contains(systemUser)||repairOrder.getAssignPositions().contains(position))){
                    jsonArray.add("takingButton");
                } else if (!repairOrder.getAssign()) {
                    jsonArray.add("takingButton");
                }
            }

        } else if ("IN_AUDITING".equals(statusCode)) {
            if (signEnterpriseId.equals(sessionEnterprise.getId().toString())&&repairOrder.getRepairOrderTypeEnum().getCode().equals("_400_ORDER")&&(repairOrder.getSignDate()==null||repairOrder.getConfirmDate()==null)) {
                if (!repairOrder.isCheckRepair() && systemUser.getId().equals(repairOrder.getReceiveUser().getId())&&repairOrder.getConfirmDate() == null) {//为我确认维修并且当前登陆人是报修人的时候.可以确认维修
                    //确认维修页面
                    jsonArray.add("reconfirmButton");//维修确认
                } else if (systemUser.getId().equals(repairOrder.getReceiveUser().getId())&&repairOrder.getConfirmDate()!=null&&repairOrder.getSignDate()==null) {
                    jsonArray.add("reEnter");//重新输入
                    jsonArray.add("confirmSign");//确认签字
                }
            } else {
                if (systemAuthorityBiz.hasAuthAuthority(auditAuthority, systemUser.getId(), sessionEnterprise.getId())) {
                    if (organization != null) {
                        if (repairOrder.getAuditUser() != null || repairOrder.getAuditPosition() != null) {
                            if ((repairOrder.getAuditOrganization() == organization && repairOrder.getAuditUser() == systemUser)) {
                                jsonArray.add("passButton");
                                jsonArray.add("rejectButton");
                            } else if (repairOrder.getAuditOrganization() == organization && repairOrder.getAuditPosition() == systemUser.getPosition(sessionEnterprise, systemUser.getPositionSet())) {
                                jsonArray.add("passButton");
                                jsonArray.add("rejectButton");
                            }
                        }
                    }

                    if (flowArray.size() > 0 && auditLevel + 1 == flowArray.size()) {
                        jsonObject.put("final", true);
                    } else {
                        jsonObject.put("final", false);
                    }
                }
            }


        } else if ("WAIT_PRESENCE".equals(statusCode)) {
            // 添加转单权限
            // 如果这个人有批量转单的权限，就给他添加转单的权限判断等操作，如果他没有批量转单的权限，就不给他有转单权限
            // 转单权限
            if (systemAuthorityBiz.hasAuthAuthority(transfersHorityName, systemUser.getId(), sessionEnterprise.getId())) {
                jsonArray.add("transferButton");
            }

            if (repairOrder.getReceiveUser() != null && repairOrder.getReceiveUser() == systemUser) {
                jsonArray.add("presenceButton");
            }
        } else if ("WAIT_CONFIRM_FAULT".equals(statusCode)) {
            if (repairOrder.getReceiveUser() != null && repairOrder.getReceiveUser() == systemUser) {
                jsonArray.add("confirmButton");
            }
        } else if ("UNFINISHED".equals(statusCode)) {

            // 添加转单权限  同上WAIT_PRESENCE
            // 如果这个人有批量转单的权限，就给他添加转单的权限判断等操作，如果他没有批量转单的权限，就不给他有转单权限
            // 转单权限
            if (systemAuthorityBiz.hasAuthAuthority(transfersHorityName, systemUser.getId(), sessionEnterprise.getId())) {
                jsonArray.add("transferButton");
            }

            if (repairOrder.getReceiveUser() != null && repairOrder.getReceiveUser() == systemUser) {
                jsonArray.add("submitButton");
                jsonArray.add("saveButton");
            }
        } else if ("REJECTED".equals(statusCode)) {
            if (repairOrder.getReceiveUser() != null && repairOrder.getReceiveUser() == systemUser) {
                jsonArray.add("presenceButton");
            }
        }
        jsonObject.put("buttons", jsonArray);
        jsonObject.put("isFocus", isFocus(repairOrderId, systemUser, sessionEnterprise));
        jsonObject.put("auditLog", aduitLog(repairOrderId, sessionEnterprise));
        //如果是确认签字中，跳转到签字版页面。400维修，审批中，已经确认维修，未签字
        if (signEnterpriseId.equals(sessionEnterprise.getId().toString())&&repairOrder.getRepairOrderTypeEnum().getCode().equals("_400_ORDER") && repairOrder.getRepairOrderStatusEnum().getCode().equals("IN_AUDITING") &&
                repairOrder.isCheckRepair() && repairOrder.getSignDate() == null && systemUser.getId().equals(repairOrder.getReceiveUser().getId())) {
            jsonObject.put("signConfirm", true);

        } else {
            jsonObject.put("signConfirm", false);
        }
        return ResultUtil.success(jsonObject);

    }

    public ResultDto removePartner(String id) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        repairPartnerBiz.deleteLogic(repairPartnerBiz.findModel(StringConverters.null2Long(id)));
        return ResultUtil.success();
    }

    public ResultDto transferList(String searchParam, String pageIndex, String pageSize) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        systemUser = systemUserBiz.findModel(systemUser.getId());
        Set<SystemUserOrganization> systemUserOrganizationSet = systemUser.getSystemUserOrganizationSet();
        //所属部门
        Organization organization = null;
        boolean leader = false;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationSet)) {
            for(SystemUserOrganization x:systemUserOrganizationSet){
                if(x.getOrganization().getEnterprise().getId().equals(sessionEnterprise.getId())){
                    leader = x.isLeader();
                    organization=x.getOrganization();
                }
            }
        }

        return ResultUtil.success(dao.transferList(searchParam, pageIndex, pageSize, systemUser, sessionEnterprise,organization));
    }

    public ResultDto repairHistory(String facilityId, String pageIndex, String pageSize) {
        JSONObject result = new JSONObject();
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("facilityId", facilityId);
        queryParam.getSqlMap().put("repairOrderStatus", "COMPLETED");
        List<RepairOrder> list = findList(queryParam);

        JSONArray rows = new JSONArray();
        for (RepairOrder repairOrder : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("createDate", DateTimeUtils.format(repairOrder.getCreateDate(), DateTimeUtils.format(repairOrder.getCreateDate(), "MM-dd HH:mm")));
            jsonObject.put("reportContent", StringConverters.null2String(repairOrder.getReportContent()));
            jsonObject.put("reportAddress", StringConverters.null2String(repairOrder.getReportAddress()));
            jsonObject.put("orderStatus", repairOrder.getRepairOrderStatusEnum().getName());
            jsonObject.put("reportCode", repairOrder.getReportCode());
            jsonObject.put("reportUser", repairOrder.getReportUser() == null ? "" : repairOrder.getReportUser().getUserName());
            jsonObject.put("id", repairOrder.getId());

            //标签设置
            Date now = new Date();
            JSONArray tags = new JSONArray();
            JSONObject tagObject = new JSONObject();
            if (now.getTime() > repairOrder.getRequireFinishTime().getTime()) {
                tags.add(tagObject("逾期", "full-orange"));
            }
            if (repairOrder.getReportLevel() != null) {
                tags.add(tagObject(repairOrder.getReportLevel().getGrade(), "orange"));
            }

            if (repairOrder.getAssign()) {
                tags.add(tagObject("被指派", "blue"));
            }

            if ("IN_AUDITING".equals(repairOrder.getRepairOrderStatusEnum().getCode())) {
                tags.add(tagObject(NumberUtil.convert(repairOrder.getAuditLevel() + 1) + "审", "blue"));
            }
            if (StringUtils.isNotBlank(repairOrder.getRepairOrderTypeEnum().getCode())) {
                if ("COMMON_ORDER".equals(repairOrder.getRepairOrderTypeEnum().getCode())) {
                    tags.add(tagObject("普通", "blue"));
                } else if ("FACILITY_ORDER".equals(repairOrder.getRepairOrderTypeEnum().getCode())) {
                    tags.add(tagObject("设备", "blue"));
                }
            }
            if (repairOrder.getReportMajor() != null) {
                tags.add(tagObject(repairOrder.getReportMajor().getPropertyName(), "blue"));
            }

            //设备标签
            if (repairOrder.getFacility() != null && repairOrder.getFacility().getFacilityCat() != null) {
                FacilityCat rootCat = facilityCatBiz.findRootCat(repairOrder.getFacility().getFacilityCat().getId());
                tags.add(tagObject(repairOrder.getFacility().getFacilityCat().getCatName(), "blue"));
                tags.add(tagObject(rootCat.getCatName(), "blue"));
            }
            jsonObject.put("tags", tags);
            rows.add(jsonObject);
        }
        result.put("rows", rows);
        Map<String, String> queryHashMap = new HashMap<>();
        queryHashMap.put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryHashMap.put("facilityId", facilityId);
        queryHashMap.put("repairOrderStatus", "COMPLETED");
        result.put("records", totalRecord(queryHashMap));
        return ResultUtil.success(result);
    }


    public ResultDto process(String repairOrderId) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        Map<String, String> queryHashMap = new HashMap<>();
        queryHashMap.put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryHashMap.put("repairOrderId", repairOrderId);
        queryHashMap.put("repairOrderLogOperation", "AUDIT");


        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("repairOrderId", repairOrderId);
        queryParam.setSqlOrder("order by id");
        List<RepairOrderLog> repairOrderLogs = repairOrderLogBiz.findList(queryParam);
        JSONArray jsonArray = new JSONArray();
        int count = 1;
        for (RepairOrderLog repairOrderLog : repairOrderLogs) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("createDate", CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(repairOrderLog.getCreateDate()), ""));
            if ("AUDIT".equals(repairOrderLog.getRepairOrderLogOperationEnum().getCode())) {
                    if (count == 0) { count = 1; } // 优化零级审核
                    jsonObject.put("operation", NumberUtil.convert(count) + "级" + repairOrderLog.getRepairOrderLogOperationEnum().getName());
                    jsonObject.put("userName", repairOrderLog.getUserName());
                    jsonArray.add(jsonObject);
                    count++;
            } else {
                jsonObject.put("operation", repairOrderLog.getRepairOrderLogOperationEnum().getName());
                jsonObject.put("userName", repairOrderLog.getUserName());
                if ("REJECT".equals(repairOrderLog.getRepairOrderLogOperationEnum().getCode())) {//驳回之后回到一级审核
                    count = 1;
                }
                jsonArray.add(jsonObject);

            }
        }
        JSONObject result = new JSONObject();
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }

    public ResultDto taking(String repairOrderId) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        RepairOrder repairOrder = findModel(StringConverters.null2Long(repairOrderId));
        if (repairOrder == null) {
            return ResultUtil.error();
        }
        //修改维修单状态
        repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.WAIT_PRESENCE);
        repairOrder.setReceiveUser(systemUser);
        repairOrder.setReceiveDate(new Date());
        addOrUpdate(repairOrder);
        //日志
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.TAKING, sessionEnterprise, null);

        //推送消息
        SystemUser reportUser = repairOrder.getReportUser();
        String content = "维修单:" + repairOrder.getReportCode() + ",已被" + systemUser.getUserName() + "接单。";
        List<Long> ids = new ArrayList<>();
        ids.add(reportUser.getId());
        planMessageSendBiz.senMsg(repairOrder.getId(), "repair", sessionEnterprise, ids, content);

        return ResultUtil.success();
    }

    public ResultDto getDictSelect(String typeCode) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        return ResultUtil.success(dictInfoBiz.getDictSelect(sessionEnterprise, typeCode));
    }

    public static long getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long diff = endDate.getTime() - nowDate.getTime();
        long min = diff % nd % nh / nm;
        return min;
    }

    public ResultDto getOrdersByCode(String repairCode) {
        JSONObject jsonObject = new JSONObject();
        JSONArray resultArray = new JSONArray();
        if (StringUtils.isNotBlank(repairCode)) {
            JSONArray jsonArray = JSONArray.parseArray(repairCode);
            for (Object object : jsonArray) {
                QueryParam queryParam = new QueryParam();
                queryParam.getSqlMap().put("reportCode", StringConverters.null2String(object));
                queryParam.getSqlMap().put("repairSource", "CUSTOMER_REPORT");
                List<RepairOrder> list = dao.findList(queryParam);
                if (CollectionUtils.isNotEmpty(list)) {
                    resultArray.add(list.get(0).toJSONObject());
                }
            }
        }
        jsonObject.put("rows", resultArray);
        return ResultUtil.success(jsonObject);
    }

    public JSONArray getHoursChartsData(String startDateTime, String endDateTime, String organizationId,String enterpriseId) {
        JSONArray result = new JSONArray();
        List<Object> hoursChartsData = dao.getHoursChartsData(startDateTime, endDateTime, enterpriseId, organizationId);
        for (Object data : hoursChartsData) {
            result.add(StringConverters.null2Int(data));
        }
        return result;
    }

    private JSONObject tagObject(String name, String color) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("color", color);
        return jsonObject;
    }

    public ResultDto getUser(String pageIndex, String pageSize, String userName, String userIds) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        String userHql = "select obj from SystemUser obj where obj.deleteStatus is false and obj.operationRole='common' and " +
                "exists( select er from obj.enterpriseSet er" +
                " where er.id=" + enterprise.getId() + ")";
        if (!StringConverters.null2String(userName).equals("")) {
            userHql += " and obj.userName like '%" + userName + "%'";
        }

        if (!StringConverters.null2String(userIds).equals("")) {
            String ids = "";
            for (Object object : JSONArray.parseArray(userIds)) {
                if (ids.equals("")) {
                    ids = StringConverters.null2String(object);
                } else {
                    ids += "," + StringConverters.null2String(object);
                }
            }
            if (!StringConverters.null2String(ids).equals("")) {
                userHql += "  and obj.id not in(" + StringConverters.null2String(ids) + ")";
            }

        }
        JSONArray jsonArray = new JSONArray();
        for (SystemUser systemUser : systemUserBiz.hqlExcute(userHql, queryParam)) {
            jsonArray.add(systemUser.toJSONObject());
        }
        return ResultUtil.success(jsonArray);
    }

    public ResultDto getPosition(String pageIndex, String pageSize, String positionIds) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        String posHql = "select obj from Position obj where obj.deleteStatus is false and obj.enterprise.id=" + enterprise.getId();
        if (!StringConverters.null2String(positionIds).equals("")) {
            String ids = "";
            for (Object object : JSONArray.parseArray(positionIds)) {
                if (ids.equals("")) {
                    ids = StringConverters.null2String(object);
                } else {
                    ids += "," + StringConverters.null2String(object);
                }
            }
            if (!StringConverters.null2String(ids).equals("")) {
                posHql += "  and obj.id not in(" + StringConverters.null2String(ids) + ")";
            }

        }
        JSONArray jsonArray = new JSONArray();
        for (Position position : positionBiz.hqlExcute(posHql, queryParam)) {
            jsonArray.add(position.toJSONObject());
        }
        return ResultUtil.success(jsonArray);
    }

    public ResultDto assignUsers(String assignIds, String orderId) {
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == sessionUser || null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        JSONArray jsonArray = JSONArray.parseArray(assignIds);
        RepairOrder repairOrder = dao.findModel(StringConverters.null2Long(orderId));
        Set<SystemUser> systemUsers = new HashSet<>();
        for (Object id : jsonArray) {
            SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(id));
            if (systemUser != null) {
                systemUsers.add(systemUser);
            }
        }
        repairOrder.setAssign(Boolean.TRUE);
        repairOrder.setAssignTypeEnum(AssignTypeEnum.USER);
        repairOrder.setAssignUsers(systemUsers);
        dao.update(repairOrder);
        //操作日志
        repairOrderLogBiz.addLog(repairOrder, sessionUser, RepairOrderLogOperationEnum.ASSIGN_USER, enterprise, null);
        return ResultUtil.success();
    }

    public ResultDto assignPositions(String assignIds, String orderId) {
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == sessionUser || null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        JSONArray jsonArray = JSONArray.parseArray(assignIds);
        RepairOrder repairOrder = dao.findModel(StringConverters.null2Long(orderId));
        Set<Position> positions = new HashSet<>();
        for (Object id : jsonArray) {
            Position position = positionBiz.findModel(StringConverters.null2Long(id));
            if (positions != null) {
                positions.add(position);
            }
        }
        repairOrder.setAssign(Boolean.TRUE);
        repairOrder.setAssignTypeEnum(AssignTypeEnum.POSITION);
        repairOrder.setAssignPositions(positions);
        dao.update(repairOrder);
        //操作日志
        repairOrderLogBiz.addLog(repairOrder, sessionUser, RepairOrderLogOperationEnum.ASSIGN_POSITION, enterprise, null);
        return ResultUtil.success();
    }

    /**
     * 维修工单(今日)
     *
     * @return
     */
    public JSONObject repairOrderCount(String enterpriseIds) {
        JSONObject result = new JSONObject();
        if (StringUtils.isBlank(enterpriseIds)) {
            result.put("todayCount", 0);
            result.put("finishCount", 0);
            result.put("repairingCount", 0);
            return result;
        }
        String todayStr = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getBeginOfDay(new Date()));
        //总工单数(今日创建的维修单数)
        QueryParam queryParam1 = new QueryParam();
        queryParam1.getSqlMap().put("enterpriseIds", enterpriseIds);
        queryParam1.getSqlMap().put("beforeCreateDate", todayStr);
        Long todayCount = this.totalRecord(queryParam1.getSqlMap());
        //维修完成(今日完成的维修单数)
        QueryParam queryParam2 = new QueryParam();
        queryParam2.getSqlMap().put("enterpriseIds", enterpriseIds);
        queryParam2.getSqlMap().put("repairOrderStatus", RepairOrderStatusEnum.COMPLETED.getCode());
        queryParam2.getSqlMap().put("beforeRepairFinishTime", todayStr);
        Long finishCount = this.totalRecord(queryParam2.getSqlMap());
        //维修中(已接单还未完成的维修单数)
        QueryParam queryParam3 = new QueryParam();
        queryParam3.getSqlMap().put("enterpriseIds", enterpriseIds);
        String orderStatus = RepairOrderStatusEnum.WAIT_PRESENCE.getCode()
                + "," + RepairOrderStatusEnum.WAIT_CONFIRM_FAULT.getCode()
                + "," + RepairOrderStatusEnum.UNFINISHED.getCode()
                + "," + RepairOrderStatusEnum.REJECTED.getCode()
                + "," + RepairOrderStatusEnum.IN_AUDITING.getCode();
        queryParam3.getSqlMap().put("repairOrderStatus", orderStatus);
        Long repairingCount = this.totalRecord(queryParam3.getSqlMap());

        result.put("todayCount", todayCount);
        result.put("finishCount", finishCount);
        result.put("repairingCount", repairingCount);
        return result;
    }

    public ResultDto inspectionPresence(String presencePhotos, String repairOrderId, String longitude, String latitude) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        if (StringUtils.isBlank(presencePhotos)) {
            return ResultUtil.error("请先拍照");
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("id", repairOrderId);
        List<RepairOrder> repairOrders = findList(queryParam);
        if (CollectionUtils.isEmpty(repairOrders)) {
            return ResultUtil.error("请传入正确的参数");
        }

        JSONArray photos = JSONArray.parseArray(presencePhotos);
        Set<Resource> set = new HashSet<>();
        for (Object object : photos) {
            Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
            resource.setEnterprise(sessionEnterprise);
            resource.setResourceName("到场照片");
            resourceBiz.addOrUpdate(resource);
            set.add(resource);
        }
        RepairOrder repairOrder = repairOrders.get(0);
        if (repairOrder.getLevel() > 0 && StringUtils.isNotBlank(repairOrder.getFlow())) {
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.IN_AUDITING);
        } else {
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.COMPLETED);
        }
        repairOrder.setPresencePhoto(set);
        repairOrder.setPresenceTime(new Date());
        repairOrder.setMark(false);
        repairOrder.setRepairFinishTime(new Date());
        if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
            repairOrder.setLatitude(new BigDecimal(latitude));
            repairOrder.setLongitude(new BigDecimal(longitude));
        }
        addOrUpdate(repairOrder);

        //日志
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.PRESENCE, sessionEnterprise, null);

        return ResultUtil.success();
    }

    public JSONObject countScore(String enterpriseId, String systemUserId) {
        JSONObject result = new JSONObject();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("systemUserId", systemUserId);
        List<Long> ids = new ArrayList<>();
        String idArray = com.useeinfo.framework.sugar.func.lang.StringUtils.strip(ids.toString(), "[]");
        List<Enterprise> enterprises = enterpriseBiz.findList(queryParam);
        for (Enterprise enterprise : enterprises) {
            ids.add(enterprise.getId());
        }
        List<String> list = new ArrayList<>();
        list.add("4");
        list.add("5");
        int score_0 = StringConverters.null2Int(dao.countScore("0", ids).get(0));
        int score_1 = StringConverters.null2Int(dao.countScore("1", ids).get(0));
        int score_2 = StringConverters.null2Int(dao.countScore("2", ids).get(0));
        int score_3 = StringConverters.null2Int(dao.countScore("3", ids).get(0));
        int score_4 = StringConverters.null2Int(dao.countScore("4", ids).get(0));
        int score_5 = StringConverters.null2Int(dao.countScore("5", ids).get(0));
        int score_achieve = StringConverters.null2Int(dao.countScore(StringUtils.strip(list.toString(), "[]"), ids).get(0));
        int totalScore = StringConverters.null2Int(dao.countScore("", ids).get(0));
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("num", score_5);
        jsonObject.put("name", "A");
        jsonObject.put("percent", DataHandleUtil.division(score_5, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_4);
        jsonObject.put("name", "B");
        jsonObject.put("percent", DataHandleUtil.division(score_4, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_3);
        jsonObject.put("name", "C");
        jsonObject.put("percent", DataHandleUtil.division(score_3, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_2);
        jsonObject.put("name", "D");
        jsonObject.put("percent", DataHandleUtil.division(score_2, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_1);
        jsonObject.put("name", "E");
        jsonObject.put("percent", DataHandleUtil.division(score_1, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_0);
        jsonObject.put("name", "F");
        jsonObject.put("percent", DataHandleUtil.division(score_0, totalScore));
        jsonArray.add(jsonObject);
        result.put("scores", jsonArray);
        result.put("totalNum", totalScore);
        result.put("achieve", DataHandleUtil.division(score_achieve, totalScore));
        return result;
    }

    public ResultDto partnerDetail(String repairOrderId, String userId) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("partnerId", userId);
        queryParam.getSqlMap().put("repairOrderId", repairOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        List<RepairPartner> repairPartners = repairPartnerBiz.findList(queryParam);
        if (CollectionUtils.isNotEmpty(repairPartners)) {
            result = repairPartners.get(0).toJSONObject();
        }
        return ResultUtil.success(result);
    }

    /**
     * 设备故障发生次数TOP10
     *
     * @param enterpriseIds
     * @return
     */
    public JSONArray repairTop10(String enterpriseIds, String startDate, String endDate) {
        JSONArray rows = new JSONArray();
        if (StringUtils.isBlank(enterpriseIds)) {
            return rows;
        }
        List<Object[]> objects = dao.repairTop10(enterpriseIds, startDate, endDate);
        for (Object obj[] : objects) {
            JSONObject json = new JSONObject();
            Long facilityId = obj[0] == null ? null : ((BigInteger) obj[0]).longValue();
            Integer totalCount = ((BigInteger) obj[1]).intValue();
            if (facilityId != null) {
                Facility facility = facilityBiz.findModel(facilityId);
                json.put("facilityName", facility.getName());
            } else {
                json.put("facilityName", "未分配");
            }
            json.put("facilityId", facilityId);
            json.put("totalCount", totalCount);
            rows.add(json);
        }
        return rows;
    }

    /**
     * 正在维修中的设备
     *
     * @return
     */
    public JSONArray repairFacilityCount(String enterpriseIds) {
        JSONArray rows = new JSONArray();
        if (StringUtils.isBlank(enterpriseIds)) {
            return rows;
        }
        List<Object[]> objects = dao.repairFacilityCount(enterpriseIds);
        for (Object obj : objects) {
            net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(obj);
            Long facilityId = AnalysisObjectList.getJsonLong(j, 0);
            if (facilityId > 0) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("facilityId", facilityId + "");
                rows.add(jsonObject);
            }
        }
        return rows;
    }

    /**
     * dashboard-故障严重程度列表
     */
    public JSONArray getFailureSeverityDashBoard(Map<String, Object> dataMap) {
        JSONArray jsonArray = new JSONArray();
        List objects = dao.getFailureSeverityDashBoard(dataMap);
        if (CollectionUtils.isNotEmpty(objects)) {
            try {
                for (Object object : objects) {
                    JSONObject jsonObject = new JSONObject();
                    net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(object);
                    jsonObject.put("grade", AnalysisObjectList.getJsonString(j, 0));
                    jsonObject.put("num", AnalysisObjectList.getJsonString(j, 2));
                    jsonArray.add(jsonObject);
                }
            } catch (Exception e) {
                logger.info("数据异常");
            }
        }
        return jsonArray;
    }

    /**
     * dashboard-故障严重程度总数
     */
    public Long getFailureSeverityTotalDashBoard(Map<String, Object> dataMap) {
        List objects = dao.getFailureSeverityTotalDashBoard(dataMap);
        if (CollectionUtils.isNotEmpty(objects)) {
            try {
                return StringConverters.ToLong(objects.get(0).toString());
            } catch (Exception e) {
                logger.info("数据异常");
            }
        }
        return 0L;
    }

    /**
     * dashboard-设备故障发生次数统计TOP10
     */
    public JSONArray getStatisticsEquipmentFailuresDashBoard(Map<String, Object> dataMap) {
        JSONArray jsonArray = new JSONArray();
        List objects = dao.getStatisticsEquipmentFailuresDashBoard(dataMap);
        if (CollectionUtils.isNotEmpty(objects)) {
            try {
                for (Object object : objects) {
                    JSONObject jsonObject = new JSONObject();
                    net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(object);
                    jsonObject.put("deviceName", AnalysisObjectList.getJsonString(j, 0));
                    jsonObject.put("num", AnalysisObjectList.getJsonString(j, 1));
                    jsonArray.add(jsonObject);
                }
            } catch (Exception e) {
                logger.info("数据异常");
            }
        }
        return jsonArray;
    }

    public JSONArray getTags(RepairOrder repairOrder, SystemUser systemUser, String status) {
        return dao.getTags(repairOrder, systemUser, status);
    }

    /**
     * dashboard-获取分区响应时间-维修
     */
    public JSONArray getRepairOrderResponseTime(Map<String, Object> dataMap) {
        JSONArray jsonArray = new JSONArray();
        List objects = dao.getRepairOrderResponseTime(dataMap);
        if (CollectionUtils.isNotEmpty(objects)) {
            try {
                for (Object object : objects) {
                    net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(object);
                    jsonArray.add( AnalysisObjectList.getJsonString(j, 2));
                }
            } catch (Exception e) {
                logger.info("数据异常");
            }
        }
        return jsonArray;
    }

    /**
     * 分区域维修完成率
     *
     * @param enterpriseIds
     * @return
     */
    public JSONObject areaPercent(String enterpriseIds, String startDate, String endDate) {
        JSONObject rows = new JSONObject();
        if (StringUtils.isBlank(enterpriseIds)) {
            return rows;
        }
        List<Object[]> objects = dao.areaPercent(enterpriseIds, startDate, endDate);
        JSONArray nameArray = new JSONArray();
        JSONArray countArray = new JSONArray();
        JSONArray percentArray= new JSONArray();
        for (Object obj[] : objects) {


            Long areaRootId = obj[0] == null ? null : ((BigInteger) obj[0]).longValue();
            Integer totalCount = ((BigInteger) obj[1]).intValue();
            if (areaRootId != null) {
                Area area = areaBiz.findModel(areaRootId);
                nameArray.add(area.getAreaName());
            } else {
                nameArray.add( "未分配");
            }
            countArray.add(totalCount);
            //再查完成百分比
            Long finishedCount = dao.areaPercentFinishedCount(enterpriseIds, startDate, endDate, areaRootId == null ? "" : areaRootId.toString());
            if (finishedCount == null || finishedCount == 0) {
                percentArray.add( "0%");
            } else {
                long percentNum = (finishedCount * 100) / totalCount;
                percentArray.add(percentNum + "%");
            }
        }
        rows.put("nameArray",nameArray);
        rows.put("countArray",countArray);
        rows.put("percentArray",percentArray);
        return rows;
    }

    //实时工时
    public ResultDto nowWorkHours(String id) {
        JSONObject jsonObject = new JSONObject();
        long totalHours = 0;
        RepairOrder repairOrder = dao.findModel(StringConverters.null2Long(id));
        if (repairOrder == null) {
            jsonObject.put("totalHours", totalHours);
            jsonObject.put("receiveHours", totalHours);
            return ResultUtil.success(jsonObject);
        }
        if (repairOrder.getRepairOrderStatusEnum().getCode().equals("UNFINISHED") || repairOrder.getRepairOrderStatusEnum().getCode().equals("WAIT_CONFIRM_FAULT")) {
            totalHours = DateTimeUtils.getDistanceMinutes(repairOrder.getPresenceTime(), new Date());
        }
        jsonObject.put("totalHours", repairOrder.getTotalWorkingHours() + totalHours);
        jsonObject.put("receiveHours", repairOrder.getWorkingHours() + totalHours);
        return ResultUtil.success(jsonObject);
    }

    //维修确认,在审核列表中确认
    public ResultDto confirmRepair(String id) {
        RepairOrder repairOrder = dao.findModel(StringConverters.null2Long(id));
        if (!repairOrder.getRepairOrderTypeEnum().getCode().equals("_400_ORDER") || !repairOrder.getRepairOrderStatusEnum().getCode().equals("IN_AUDITING")) {
            return ResultUtil.error("该状态下无法确认维修");
        }
        repairOrder.setCheckRepair(true);
        repairOrder.setConfirmDate(new Date());
        this.addOrUpdate(repairOrder);
        return ResultUtil.success();
    }

    //保存签字图片
    public ResultDto saveSignPic(MultipartFile file, String id, Enterprise sessionEnterprise) {
        RepairOrder repairOrder = dao.findModel(StringConverters.null2Long(id));
        if (!repairOrder.getRepairOrderTypeEnum().getCode().equals("_400_ORDER")) {
            return ResultUtil.error("该状态下无法确认维修");
        }
        Resource resource = new Resource();
        String savePath = "";
        //上传图片
        savePath = FileUtils.fileUpload(file, ConstantKeyFilePath.REPAIR_IMG_DIR, ConstantKeyFilePath.REPAIR_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
        resource.setResourceName("设备报修图片");
        resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
        resource.setResourceName("签字图片");
        resource.setPath(savePath);
        resource.setEnterprise(sessionEnterprise);
        resource.setCreateDate(new Date());
        //把签字照片放在完成照片里
        resourceBiz.addOrUpdate(resource);
        Set<Resource> set = repairOrder.getFinishPhoto();
        set.add(resource);
        repairOrder.setFinishPhoto(set);//把签名图片存入完成照片中
        repairOrder.setSignDate(new Date());//签名时间
        //判断是否有审核流，没有则变成已完成
        if (StringUtils.isBlank(repairOrder.getFlow())) {
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.COMPLETED);
        }
        this.addOrUpdate(repairOrder);
        return ResultUtil.success();
    }
}
